<template>
  <div class="login-container">
    <div class="login-form">
      <h1>用户登录</h1>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input 
            type="text" 
            id="username" 
            v-model="loginForm.username" 
            required
            placeholder="请输入用户名"
          />
          <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
        </div>
        
        <div class="form-group">
          <label for="password">密码</label>
          <input 
            type="password" 
            id="password" 
            v-model="loginForm.password" 
            required
            placeholder="请输入密码"
          />
          <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
        </div>
        
        <div v-if="errors.general" class="error-message general-error">{{ errors.general }}</div>
        
        <button type="submit" :disabled="isLoading">
          <span v-if="isLoading">登录中...</span>
          <span v-else>登录</span>
        </button>
        
        <div class="register-link">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';

const router = useRouter();
const userStore = useUserStore();

const loginForm = ref({
  username: '',
  password: ''
});

const errors = ref({
  username: '',
  password: '',
  general: ''
});

const isLoading = ref(false);

const handleLogin = async () => {
  // 重置错误信息
  errors.value = {
    username: '',
    password: '',
    general: ''
  };
  
  // 表单验证
  if (!loginForm.value.username) {
    errors.value.username = '请输入用户名';
    return;
  }
  
  if (!loginForm.value.password) {
    errors.value.password = '请输入密码';
    return;
  }
  
  try {
    isLoading.value = true;
    
    console.log('登录表单数据:', loginForm.value);
    
    // 使用表单中输入的用户名和密码
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: loginForm.value.username,
        password: loginForm.value.password
      })
    });
    
    console.log('登录响应状态:', response.status);
    
    // 尝试解析响应，即使状态码不是2xx
    const responseText = await response.text();
    console.log('登录响应文本:', responseText);
    
    let data;
    try {
      data = JSON.parse(responseText);
      console.log('登录响应数据:', data);
    } catch (e) {
      console.error('解析响应JSON失败:', e);
      throw new Error('服务器返回的数据格式不正确');
    }
    
    // 检查响应状态
    if (!response.ok) {
      // 如果响应不成功，抛出错误
      throw new Error(data.message || '登录失败，请检查用户名和密码');
    }
    
    // 登录成功，保存token和用户信息
    localStorage.setItem('token', data.token);
    localStorage.setItem('user', JSON.stringify({
      username: data.username,
      nickname: data.nickname,
      roles: data.roles
    }));
    
    // 更新用户状态
    userStore.setUser({
      username: data.username,
      nickname: data.nickname,
      roles: data.roles,
      token: data.token
    });
    
    // 登录成功后跳转到首页
    router.push('/');
  } catch (error) {
    console.error('登录错误:', error);
    errors.value.general = error.message || '登录失败，请稍后再试';
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 20px;
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: white;
}

h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  border-color: #4CAF50;
  outline: none;
}

button {
  width: 100%;
  padding: 12px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.error-message {
  color: #f44336;
  font-size: 14px;
  margin-top: 5px;
}

.general-error {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #ffebee;
  border-radius: 4px;
  text-align: center;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
}

.register-link a {
  color: #4CAF50;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style> 